package com.azxcrm.project.monitor.workflow.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azxcrm.common.utils.StringUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.web.controller.BaseController;
import com.azxcrm.framework.web.domain.Message;
import com.azxcrm.framework.web.page.TableDataInfo;
import com.azxcrm.project.monitor.workflow.common.CommonService;
import com.azxcrm.project.monitor.workflow.domain.WorkFlow;
import com.azxcrm.project.monitor.workflow.domain.WorkFlowApply;
import com.azxcrm.project.monitor.workflow.service.WorkFlowApplyService;
import com.azxcrm.project.monitor.workflow.service.WorkFlowService;

/**
 * 审批申请 控制层处理
 * 
 * @author Dustyone
 * @date 2018-08-07
 */
@Controller
@RequestMapping("/module/workFlowApply")
public class WorkFlowApplyController extends BaseController {
	private String prefix = "module/workFlowApply";

	@Autowired
	private WorkFlowApplyService workFlowApplyService;

	@Autowired
	private WorkFlowService workFlowService;

	@Autowired
	private CommonService commonService;

	@Autowired
	private HistoryService historyService;
	
	@Autowired
	private RepositoryService repositoryService;
	
	@Autowired
	private ProcessEngine processEngine;
	
	@Autowired
	private RuntimeService runtimeService;
	
	/**
	 * 业务员角色
	 */
	@Value("${crm.role.salesman}")
	private String salesman;
	
	/**
	 * 财务
	 */
	@Value("${crm.role.treasurer}")
	private String treasurer;
	
	/**
	 * 管理员
	 */
	@Value("${crm.role.admin}")
	private String admin;
	
	@GetMapping()
	@RequiresPermissions("module:workFlowApply:view")
	String workFlowApply(Model model,String type) {
		return prefix + "/workFlowApply";
	}

	/**
	 * 查询审批申请列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("module:workFlowApply:list")
	@ResponseBody
	public TableDataInfo list(WorkFlowApply workFlowApply) {

		setPageInfo(workFlowApply);
		if(ShiroUtils.hasRole(salesman)){
			//业务员查看自己发起的审批请求
			workFlowApply.setUserId(ShiroUtils.getUserId().intValue());
		}
		List<WorkFlowApply> list = workFlowApplyService.selectWorkFlowApplyList(workFlowApply);
		return getDataTable(list);
	}

	/**
	 * 新增审批申请
	 */
	@GetMapping("/add")
	@RequiresPermissions("module:workFlowApply:add")
	public String add(Model model, WorkFlow workFlow) {
		List<WorkFlow> list = workFlowService.selectWorkFlowList(workFlow);
		model.addAttribute("list", list);
		return prefix + "/add";
	}

	/**
	 * 修改审批申请
	 */
	@GetMapping("/edit/{id}")
	@RequiresPermissions("module:workFlowApply:edit")
	public String edit(@PathVariable("id") Integer id, Model model) {
		WorkFlowApply workFlowApply = workFlowApplyService.selectWorkFlowApplyById(id);
		model.addAttribute("workFlowApply", workFlowApply);
		return prefix + "/edit";
	}

	/**
	 * 保存审批申请
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("module:workFlowApply:add")
	public Message save(WorkFlowApply workFlowApply) {
		String businessId = UUID.randomUUID().toString();
		workFlowApply.setBusinessId(businessId);
		workFlowApply.setUserId(ShiroUtils.getUserId().intValue());
		// 启动流程引擎

		if (workFlowApplyService.saveWorkFlowApply(workFlowApply) > 0) {
			// 只有在新增情况下才能开启流程
			if (StringUtils.isNull(workFlowApply.getApplyId())) {
				commonService.startProcess(businessId,workFlowApply);
			}

			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 删除审批申请
	 */
	@PostMapping("/remove/{id}")
	@ResponseBody
	@RequiresPermissions("module:workFlowApply:remove")
	public Message remove(@PathVariable("id") Integer id) {
		if (workFlowApplyService.deleteWorkFlowApplyById(id) > 0) {
			return Message.ok();
		}
		return Message.error();
	}

	/**
	 * 批量删除审批申请
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("module:workFlowApply:batchRemove")
	public Message remove(@RequestParam("ids[]") Integer[] ids) {
		int rows = workFlowApplyService.batchDeleteWorkFlowApply(ids);
		if (rows > 0) {
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 
	 * @param id:processInstanceId
	 * @param response
	 */
	@GetMapping("/getProcess/{businessId}")
	@ResponseBody
	@RequiresPermissions("module:workFlowApply:flowcheck")
	public void getResourceDiagramInputStream(@PathVariable("businessId") String businessKey,HttpServletResponse response) {
        try {
        	String processInstanceId = workFlowApplyService.selectProcessInstanceIdByBizKey(businessKey);
            // 获取历史流程实例
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                        
            // 获取流程中已经执行的节点，按照执行先后顺序排序
            List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceId().asc().list();
            
            // 构造已执行的节点ID集合
            List<String> executedActivityIdList = new ArrayList<String>();
            for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
                executedActivityIdList.add(activityInstance.getActivityId());
            }
            
            // 获取bpmnModel
            BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
            // 获取流程已发生流转的线ID集合
            List<String> flowIds = commonService.getExecutedFlows(bpmnModel, historicActivityInstanceList);
            
            // 使用默认配置获得流程图表生成器，并生成追踪图片字符流
            ProcessDiagramGenerator processDiagramGenerator = processEngine.getProcessEngineConfiguration().getProcessDiagramGenerator();
            InputStream imageStream = processDiagramGenerator.generateDiagram(bpmnModel, "png", executedActivityIdList, flowIds, "宋体", "宋体", "宋体", null, 2.0);
            
         // 输出资源内容到相应对象
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = imageStream.read(b, 0, 1024)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	
	
	@GetMapping("/assign")
	@RequiresPermissions("module:workFlowApply:assign")
	public String assignTask(){
		return prefix + "/workFlowAssign";
	}
	
	/**
	 * 查询审批申请列表
	 */
	@GetMapping("/assignList")
	@RequiresPermissions("module:workFlowApply:assign")
	@ResponseBody
	public TableDataInfo myAssignmentList(WorkFlowApply workFlowApply) {

		setPageInfo(workFlowApply);
		ArrayList<WorkFlowApply> flowInfoList = new ArrayList<>();
		List<Task> list = commonService.findTaskByUserId(String.valueOf(ShiroUtils.getUserId()));
		for (Task task : list) {
			ProcessInstance result = runtimeService.createProcessInstanceQuery()
					.processInstanceId(task.getProcessInstanceId()).singleResult();
			// 获得业务流程的bussinessKey
			String businessKey = result.getBusinessKey();
			WorkFlowApply flowInfo = workFlowApplyService.selectWorkFlowApplyByBusinessId(businessKey);
			flowInfo.setTaskId(task.getId());
			//统一显示用户名
			flowInfoList.add(flowInfo);
		}
		return getDataTable(flowInfoList);
	}
	
	@GetMapping("/auditTask/{taskId}/{audit}")
	@ResponseBody
	public Message auditTask(@PathVariable("taskId") String taskId,@PathVariable("audit") String audit){
		commonService.completeTaskByUser(taskId, String.valueOf(ShiroUtils.getUserId()), audit);
		return Message.ok();
	}
}
